<template>
  <el-dialog
    v-model="visible"
    title="分发试卷"
    width="700px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="试卷信息">
        <el-card class="paper-info">
          <div class="paper-title">{{ paperInfo.title }}</div>
          <div class="paper-meta">
            <span>{{ paperInfo.subject }}</span>
            <span>{{ paperInfo.grade }}年级</span>
            <span>{{ paperInfo.total_score }}分</span>
            <span>{{ paperInfo.duration }}分钟</span>
          </div>
        </el-card>
      </el-form-item>

      <el-form-item label="分发类型" prop="distribute_type">
        <el-radio-group v-model="form.distribute_type">
          <el-radio value="class">按班级分发</el-radio>
          <el-radio value="student">按学生分发</el-radio>
          <el-radio value="department">按部门分发</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 按班级分发 -->
      <template v-if="form.distribute_type === 'class'">
        <el-form-item label="选择班级" prop="class_ids">
          <el-select
            v-model="form.class_ids"
            multiple
            placeholder="请选择班级"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="cls in classes"
              :key="cls.id"
              :label="`${cls.name} (${cls.student_count}人)`"
              :value="cls.id"
            />
          </el-select>
        </el-form-item>
      </template>

      <!-- 按学生分发 -->
      <template v-if="form.distribute_type === 'student'">
        <el-form-item label="选择学生" prop="student_ids">
          <el-select
            v-model="form.student_ids"
            multiple
            placeholder="请选择学生"
            style="width: 100%"
            filterable
            remote
            :remote-method="searchStudents"
            :loading="loadingStudents"
          >
            <el-option
              v-for="student in students"
              :key="student.id"
              :label="`${student.name} (${student.student_id})`"
              :value="student.id"
            />
          </el-select>
        </el-form-item>
      </template>

      <!-- 按部门分发 -->
      <template v-if="form.distribute_type === 'department'">
        <el-form-item label="选择部门" prop="department_ids">
          <el-select
            v-model="form.department_ids"
            multiple
            placeholder="请选择部门"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="`${dept.name} (${dept.user_count}人)`"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
      </template>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始时间" prop="start_time">
            <el-date-picker
              v-model="form.start_time"
              type="datetime"
              placeholder="选择开始时间"
              style="width: 100%"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="end_time">
            <el-date-picker
              v-model="form.end_time"
              type="datetime"
              placeholder="选择结束时间"
              style="width: 100%"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="考试设置">
        <el-card>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="允许切屏">
                <el-switch v-model="form.settings.allow_switch_screen" />
                <div class="setting-desc">是否允许学生在考试期间切换屏幕</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="随机题目">
                <el-switch v-model="form.settings.random_questions" />
                <div class="setting-desc">是否随机排列题目顺序</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="显示答案">
                <el-switch v-model="form.settings.show_answers" />
                <div class="setting-desc">交卷后是否立即显示正确答案</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="允许重考">
                <el-switch v-model="form.settings.allow_retake" />
                <div class="setting-desc">是否允许学生重新参加考试</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.settings.allow_retake">
            <el-col :span="12">
              <el-form-item label="重考次数">
                <el-input-number
                  v-model="form.settings.max_retakes"
                  :min="1"
                  :max="5"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="重考间隔">
                <el-input-number
                  v-model="form.settings.retake_interval"
                  :min="5"
                  :max="60"
                  style="width: 100%"
                />
                <span style="margin-left: 8px; color: #909399;">分钟</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form-item>

      <el-form-item label="通知设置" prop="notification">
        <el-checkbox-group v-model="form.notification">
          <el-checkbox value="email">邮件通知</el-checkbox>
          <el-checkbox value="sms">短信通知</el-checkbox>
          <el-checkbox value="system">系统通知</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="form.remarks"
          type="textarea"
          :rows="3"
          placeholder="请输入分发备注（选填）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <!-- 分发预览 -->
    <el-divider content-position="left">分发预览</el-divider>
    <div class="distribution-preview">
      <el-alert
        :title="`将向 ${targetCount} 个用户分发试卷`"
        type="info"
        :closable="false"
        show-icon
      />
      <div v-if="targetUsers.length > 0" class="target-users">
        <el-tag
          v-for="user in targetUsers.slice(0, 10)"
          :key="user.id"
          size="small"
          style="margin: 4px;"
        >
          {{ user.name }}
        </el-tag>
        <span v-if="targetUsers.length > 10" class="more-hint">
          ...还有 {{ targetUsers.length - 10 }} 个用户
        </span>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading">
        确认分发
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

interface Props {
  modelValue: boolean
  paperInfo: any
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success', data: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref()
const loading = ref(false)
const loadingStudents = ref(false)

const classes = ref([])
const students = ref([])
const departments = ref([])
const targetUsers = ref([])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const form = reactive({
  distribute_type: 'class',
  class_ids: [],
  student_ids: [],
  department_ids: [],
  start_time: '',
  end_time: '',
  settings: {
    allow_switch_screen: false,
    random_questions: false,
    show_answers: false,
    allow_retake: false,
    max_retakes: 1,
    retake_interval: 10
  },
  notification: ['system'],
  remarks: ''
})

const rules = {
  distribute_type: [
    { required: true, message: '请选择分发类型', trigger: 'change' }
  ],
  class_ids: [
    {
      required: true,
      message: '请选择班级',
      trigger: 'change',
      validator: (rule: any, value: any, callback: any) => {
        if (form.distribute_type === 'class' && (!value || value.length === 0)) {
          callback(new Error('请选择至少一个班级'))
        } else {
          callback()
        }
      }
    }
  ],
  student_ids: [
    {
      required: true,
      message: '请选择学生',
      trigger: 'change',
      validator: (rule: any, value: any, callback: any) => {
        if (form.distribute_type === 'student' && (!value || value.length === 0)) {
          callback(new Error('请选择至少一个学生'))
        } else {
          callback()
        }
      }
    }
  ],
  department_ids: [
    {
      required: true,
      message: '请选择部门',
      trigger: 'change',
      validator: (rule: any, value: any, callback: any) => {
        if (form.distribute_type === 'department' && (!value || value.length === 0)) {
          callback(new Error('请选择至少一个部门'))
        } else {
          callback()
        }
      }
    }
  ],
  start_time: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  end_time: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

const targetCount = computed(() => {
  switch (form.distribute_type) {
    case 'class':
      return form.class_ids.reduce((total, classId) => {
        const cls = classes.value.find(c => c.id === classId)
        return total + (cls?.student_count || 0)
      }, 0)
    case 'student':
      return form.student_ids.length
    case 'department':
      return form.department_ids.reduce((total, deptId) => {
        const dept = departments.value.find(d => d.id === deptId)
        return total + (dept?.user_count || 0)
      }, 0)
    default:
      return 0
  }
})

// 监听分发类型变化
watch(
  () => form.distribute_type,
  () => {
    form.class_ids = []
    form.student_ids = []
    form.department_ids = []
    targetUsers.value = []
  }
)

// 监听目标选择变化
watch(
  [() => form.class_ids, () => form.student_ids, () => form.department_ids],
  async () => {
    await updateTargetUsers()
  },
  { deep: true }
)

const fetchData = async () => {
  try {
    // TODO: 调用API获取数据
    // await Promise.all([
    //   fetchClasses(),
    //   fetchDepartments()
    // ])

    // 模拟数据
    classes.value = [
      { id: 1, name: '七年级1班', student_count: 35 },
      { id: 2, name: '七年级2班', student_count: 33 },
      { id: 3, name: '八年级1班', student_count: 38 }
    ]

    departments.value = [
      { id: 1, name: '教务处', user_count: 12 },
      { id: 2, name: '学生处', user_count: 8 },
      { id: 3, name: '年级组', user_count: 15 }
    ]
  } catch (error) {
    console.error('获取基础数据失败:', error)
  }
}

const searchStudents = async (query: string) => {
  if (!query) return

  loadingStudents.value = true
  try {
    // TODO: 调用API搜索学生
    // const response = await userApi.searchStudents({ search: query })

    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    students.value = [
      { id: 1, name: '张三', student_id: '2023001' },
      { id: 2, name: '李四', student_id: '2023002' },
      { id: 3, name: '王五', student_id: '2023003' }
    ].filter(student => student.name.includes(query) || student.student_id.includes(query))
  } catch (error) {
    console.error('搜索学生失败:', error)
  } finally {
    loadingStudents.value = false
  }
}

const updateTargetUsers = async () => {
  try {
    // TODO: 根据选择获取目标用户列表
    // let userIds = []
    // switch (form.distribute_type) {
    //   case 'class':
    //     userIds = await getClassStudents(form.class_ids)
    //     break
    //   case 'student':
    //     userIds = form.student_ids
    //     break
    //   case 'department':
    //     userIds = await getDepartmentUsers(form.department_ids)
    //     break
    // }
    // targetUsers.value = await userApi.getUsers({ ids: userIds })

    // 模拟数据
    targetUsers.value = Array.from({ length: Math.min(targetCount.value, 20) }, (_, i) => ({
      id: i + 1,
      name: `用户${i + 1}`
    }))
  } catch (error) {
    console.error('获取目标用户失败:', error)
  }
}

const handleClose = () => {
  visible.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(form, {
    distribute_type: 'class',
    class_ids: [],
    student_ids: [],
    department_ids: [],
    start_time: '',
    end_time: '',
    settings: {
      allow_switch_screen: false,
      random_questions: false,
      show_answers: false,
      allow_retake: false,
      max_retakes: 1,
      retake_interval: 10
    },
    notification: ['system'],
    remarks: ''
  })
  targetUsers.value = []
  students.value = []
  formRef.value?.clearValidate()
}

const handleConfirm = async () => {
  try {
    await formRef.value.validate()

    // 验证时间
    if (new Date(form.end_time) <= new Date(form.start_time)) {
      ElMessage.error('结束时间必须晚于开始时间')
      return
    }

    if (targetCount.value === 0) {
      ElMessage.error('请选择分发目标')
      return
    }

    await ElMessageBox.confirm(
      `确定要向 ${targetCount.value} 个用户分发试卷《${props.paperInfo.title}》吗？`,
      '确认分发',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true

    // TODO: 调用API分发试卷
    // await examPaperApi.distributePaper(props.paperInfo.id, form)

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))

    ElMessage.success('试卷分发成功')
    emit('success', { ...form, target_count: targetCount.value })
    handleClose()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('分发试卷失败:', error)
      ElMessage.error('分发试卷失败')
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.paper-info {
  .paper-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 8px;
  }

  .paper-meta {
    span {
      display: inline-block;
      margin-right: 16px;
      color: #606266;
      font-size: 14px;
    }
  }
}

.setting-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.distribution-preview {
  margin-top: 16px;

  .target-users {
    margin-top: 12px;

    .more-hint {
      color: #909399;
      font-size: 12px;
      margin-left: 8px;
    }
  }
}

:deep(.el-divider__text) {
  background-color: #f5f5f5;
}
</style>